﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Text.RegularExpressions;
using System.Data.OleDb;
using System.Timers;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System.Threading;
using Amazon.S3.Transfer;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;


namespace SecurityDev
{
    public partial class SecurInfo : Form
    {
        #region \Variable\
        string company_name = "Company_name";
        bool isAdmin;
        FileSystemWatcher _watchFolder = new FileSystemWatcher();
         
        private Amazon.S3.Transfer.TransferUtility transferUtility;

        BindingSource alertBS;
        #endregion

        #region \Functions\
        public SecurInfo()
        {
            LoginForm loginForm = new LoginForm();
            loginForm.ShowDialog();
            isAdmin = loginForm.IsAdmin;
            InitializeComponent();
            this.Text += ". " + company_name + " Edition ©";
        }

        private void SecurityDev_Load(object sender, EventArgs e)
        {
            alertBS = new BindingSource();
            alertBS.DataSource = DS.outpost.alert;
            alertsGrid.DataSource = alertBS;

            dateTimePicker1.Value = DateTime.Today.AddDays(-1);
            alertBS.Filter = "alert_date >= '" + dateTimePicker1.Value.ToShortDateString() + "'";

            alertsGrid.Columns["dvr_seq"].HeaderText = "DVR ID";
            alertsGrid.Columns["alert_seq"].HeaderText = "Alert ID";
            alertsGrid.Columns["alert_date"].HeaderText = "Date";
            alertsGrid.Columns["alert_time"].HeaderText = "Time";
            alertsGrid.Columns["alert_photo_url"].HeaderText = "Photo URL";
            alertsGrid.Columns["alert_state"].HeaderText = "State";

            var personsStr = from p in DS.outpost.person
                             select string.Format("Id: {0}; Name: {1} {2}", p.person_seq.ToString(), p.person_name, p.person_lastname);

            subscComBox.Items.Add((object)"All subscribers");
            foreach (var item in personsStr)
            {
                subscComBox.Items.Add((object)item);
            }

            if (!isAdmin)
            {
                usersToolStripMenuItem.Visible = false;
                ObjectToolStripMenuItem.Visible = false;
                subscribersToolStripMenuItem.Visible = false;
                dVRToolStripMenuItem.Visible = false;
            };

            try
            {
                startActivityMonitoring("D:/test/");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void startActivityMonitoring(string sPath)
        {
            _watchFolder.Path = sPath;
            _watchFolder.Filter = "*.jpg";
            _watchFolder.IncludeSubdirectories = true;

            _watchFolder.NotifyFilter = System.IO.NotifyFilters.DirectoryName |
                System.IO.NotifyFilters.FileName;

            _watchFolder.Created += new FileSystemEventHandler(eventRaised);

            try
            {
                _watchFolder.EnableRaisingEvents = true;
            }
            catch (ArgumentException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void eventRaised(object sender, System.IO.FileSystemEventArgs e)
        {
            notifyIcon1.ShowBalloonTip(30, "SecureDev",
                string.Format("File {0} has been created\r\n", e.FullPath),
                ToolTipIcon.Warning);

            insertData((string)e.FullPath);
        }

        string lastPath = "";

        public void insertData(string Path)
        {
            if (lastPath == Path)
            {
                return;
            }
            lastPath = Path;

            System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"config/siren.wav");
            player.Play();

            string[] directories = Path.Split('\\');

            var lastAlert = (from a in DS.outpost.alert
                             orderby a.alert_seq ascending
                             select a).LastOrDefault();

            string alert_photo_url = directories[1].ToString() + "/" + directories[2].ToString() + "/" +
                directories[3].ToString() + "/" + directories[4].ToString();

            OutpostDS.alertRow alertR;
            if (lastAlert == null)
            {
                alertR = DS.outpost.alert.AddalertRow(1,
                    DS.outpost.dvr.FindBydvr_seq(Convert.ToDecimal(directories[1])),
                    DateTime.Now.Date, DateTime.Now.TimeOfDay, Path,
                    1);
            }
            else
            {
                alertR = DS.outpost.alert.AddalertRow(lastAlert.alert_seq + 1,
                    DS.outpost.dvr.FindBydvr_seq(Convert.ToDecimal(directories[1])),
                    DateTime.Now.Date, DateTime.Now.TimeOfDay, Path, 1);
            }

            try
            {
                DS.alertAdapter.Update(DS.outpost.alert);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            /*
            #region Set Color in DataGridRow
            
            DataGridViewRow row = null;
            foreach (DataGridViewRow r in alertsGrid.Rows)
            {
                if (((decimal)r.Cells[0].Value) == alertR.alert_seq)
                {
                    row = r;
                    break;
                }
            }
            if (row != null)
            {
                row.DefaultCellStyle.Font = new Font(alertsGrid.DefaultCellStyle.Font, FontStyle.Bold);
                int priority = (int)alertR.dvrRow.objectRow.obj_priority;

                switch (priority)
                {
                    case 1:
                        row.DefaultCellStyle.BackColor = Color.Gainsboro;
                        break;
                    case 2:
                        row.DefaultCellStyle.BackColor = Color.DarkTurquoise;
                        break;
                    case 3:
                        row.DefaultCellStyle.BackColor = Color.PaleGreen;
                        break;
                    case 4:
                        row.DefaultCellStyle.BackColor = Color.Orange;
                        break;
                    case 5:
                        row.DefaultCellStyle.BackColor = Color.Red;
                        break;
                    default:
                        break;
                }
            }
            #endregion
             */

            this.transferUtility = new Amazon.S3.Transfer.TransferUtility("AKIAIOPVPT5WPQ7CIWGQ", "mub7xYzBD/6VkgxIkyQY0U+6m9DSGTWs74bP6AzM");
            var uploadRequest = new TransferUtilityUploadRequest();
            uploadRequest.FilePath = Path;
            uploadRequest.BucketName = company_name.ToLower();
            uploadRequest.Key = alert_photo_url;
            uploadRequest.AddHeader("x-amz-acl", "public-read");
            try
            {
                transferUtility.BeginUpload(uploadRequest, null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        #endregion

        #region \Tool strip\

        #region \File\
        private void PersonsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PersonsForm Customers = new PersonsForm();
            Customers.ShowDialog();

            var personsStr = from p in DS.outpost.person
                             select string.Format("Id: {0}; Name: {1} {2}", p.person_seq.ToString(), p.person_name, p.person_lastname);

            subscComBox.Items.Clear();
            subscComBox.Items.Add((object)"All subscribers");
            foreach (var item in personsStr)
            {
                subscComBox.Items.Add((object)item);
            }

        }//file-Subscribers

        private void ObjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ObjectsForm Objects = new ObjectsForm();
            Objects.ShowDialog();
        }//file-objects
        
        private void dVRToolStripMenuItem_Click(object sender, EventArgs e)//file-DVR
        {
            DVRform dvr = new DVRform();
            dvr.ShowDialog();
        }

        private void usersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Users users = new Users();
            users.ShowDialog();
        }//file-users

        private void categoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CategoriesForm category = new CategoriesForm();
            category.ShowDialog();
        }
        
        private void statisticsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Statistic users = new Statistic();
            users.ShowDialog();
        }//file-statistics
         

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }//file-Exit

        #endregion

        private void copyrightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("©SecureInfo 2013");
        }//helpToolStrip

        private void contactUsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Email us: \n siner08@gmail.com - Mykyta \n yuriy.pilinkevych@gmail.com - Yuriy");
        }//helpToolStrip

        private void switchUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(Application.ExecutablePath);
            Environment.Exit(0);
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            alertBS.Filter = "alert_date >= '" + dateTimePicker1.Value.ToShortDateString() + "'";
        }

        private void subscComBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (subscComBox.SelectedIndex == 0)
            {
                alertBS.Filter = "alert_date >= '" + dateTimePicker1.Value.ToShortDateString() + "'";
                return;
            }
            string strFilter = "";

            string person_seq = ((string)subscComBox.SelectedItem).
                Split(new string[] { "; " }, StringSplitOptions.RemoveEmptyEntries)[0].Remove(0, 4);

            var personR = DS.outpost.person.FindByperson_seq(Convert.ToDecimal(person_seq));

            var obj_seqs = (from op in DS.outpost.object_person
                            where op.person_seq == personR.person_seq
                            select op.obj_seq).ToArray();

            var dvr_seqs = (from dvr in DS.outpost.dvr
                            where MyFunc(dvr.obj_seq, obj_seqs)
                            select dvr.dvr_seq).ToArray();

            strFilter = "alert_date >= '" + dateTimePicker1.Value.ToShortDateString();

            switch (dvr_seqs.Count())
            {
                case 0:
                    strFilter += "' AND dvr_seq ='" + -1 + "'";
                    break;
                case 1:
                    strFilter += "' AND dvr_seq ='" + dvr_seqs[0] + "'";
                    break;
                default:
                    strFilter += "' AND ( dvr_seq ='" + dvr_seqs[0].ToString();
                    for (int i = 1; i < dvr_seqs.Count(); i++)
                    {
                        strFilter += "' OR dvr_seq = '" + dvr_seqs[i].ToString();
                    }
                    strFilter += "' )";
                    break;
            }
            alertBS.Filter = strFilter;
        }

        bool MyFunc(decimal d, decimal[] a)
        {
            foreach (var item in a)
            {
                if (d == item)
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region \Tray\
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Maximized;
            }
            this.Activate();
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Maximized;
            }
            this.Activate();
        }
        #endregion

        #region \Change WindowState\
        private void SecurityDev_FormClosed(object sender, FormClosingEventArgs e)
        {
            if (this.WindowState != FormWindowState.Minimized)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                notifyIcon1.ShowBalloonTip(3000, "SecureDev",
                     "You have not closed this appliation." +
                     (Char)(13) + "It has be moved to the tray.",
                     ToolTipIcon.Warning);
            }
        }

        private void SecurInfo_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                notifyIcon1.ShowBalloonTip(30, "SecureInfo",
                        "The App has be moved to the tray.",
                        ToolTipIcon.Info);
            }
            alertsGrid.AutoResizeColumns();
        }
        #endregion

        #region \Grid\
        private void alertsGrid_Paint(object sender, PaintEventArgs e)
        {
            foreach (DataGridViewRow row in alertsGrid.Rows)
            {
                if ((int)row.Cells[row.Cells.Count - 1].Value == 0)
                {
                    row.DefaultCellStyle.BackColor = Color.White;
                    continue;
                }
                row.DefaultCellStyle.Font = new Font(alertsGrid.DefaultCellStyle.Font, FontStyle.Bold);

                OutpostDS.alertRow alertR = DS.outpost.alert.FindByalert_seq((decimal)row.Cells[0].Value);
                int priority = (int)alertR.dvrRow.objectRow.obj_priority;

                switch (priority)
                {
                    case 1:
                        row.DefaultCellStyle.BackColor = Color.Gainsboro;
                        break;
                    case 2:
                        row.DefaultCellStyle.BackColor = Color.DarkTurquoise;
                        break;
                    case 3:
                        row.DefaultCellStyle.BackColor = Color.PaleGreen;
                        break;
                    case 4:
                        row.DefaultCellStyle.BackColor = Color.Orange;
                        break;
                    case 5:
                        row.DefaultCellStyle.BackColor = Color.Red;
                        break;
                    default:
                        break;
                }
            }
        }

        private void alertsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }
            this.Cursor = Cursors.AppStarting;

            decimal alert_seq = (decimal)alertsGrid.Rows[e.RowIndex].Cells["alert_seq"].Value;

            AlertDetail alertDetail = null;
            alertDetail = new AlertDetail(alert_seq);
            if (alertDetail != null)
            {
                alertDetail.ShowDialog();
                DS.outpost.alert.FindByalert_seq(alert_seq).alert_state = 0;

                try
                {
                    DS.alertAdapter.Update(DS.outpost.alert);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }            
            this.Cursor = Cursors.Default;//if need refresh()
        }

        private void alertsGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Middle)
            {
                WebInterface web = new WebInterface(alertsGrid.Rows[e.RowIndex].Cells["DVRIP"].Value.ToString());
                web.ShowDialog();
            }
        }

        #endregion

        private void regionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RegionsForm regions = new RegionsForm();
            regions.ShowDialog();
        }
        
        
    }
}


/*
 * emails.Add(alertsGrid.Rows[0].Cells["кодDataGridViewTextBoxColumn"].Value.ToString(), alertsGrid.Rows[0].Cells["PhotoUrl"].Value.ToString());
 * 
         private void sendEmail()
        {
            var customer = alertsGrid.Rows[0].Cells["Subcriber"].Value.ToString();
            var objectAddress = alertsGrid.Rows[0].Cells["Address"].Value.ToString();
            var email = alertsGrid.Rows[0].Cells["Email"].Value.ToString();
            var attach = alertsGrid.Rows[0].Cells["PhotoUrl"].Value.ToString();

            foreach (KeyValuePair<string, string> pair in this.emails)
            {
                foreach (DataGridViewRow row in alertsGrid.Rows)
                {
                    string folderPath = row.Cells[0].Value.ToString();
                    if (folderPath == pair.Key)
                    {
                        customer = alertsGrid.Rows[row.Index].Cells["Subcriber"].Value.ToString();
                        objectAddress = alertsGrid.Rows[row.Index].Cells["Address"].Value.ToString();
                        email = alertsGrid.Rows[row.Index].Cells["Email"].Value.ToString();
                        attach = alertsGrid.Rows[row.Index].Cells["PhotoUrl"].Value.ToString();
                    }
                }
            }
            StreamReader streamReader = new StreamReader("index.html");
            string text = streamReader.ReadToEnd();
            text = Regex.Replace(text, "User", customer);
            text = Regex.Replace(text, "Object_Address", objectAddress);
            foreach (KeyValuePair<string, string> pair in emails)
            {
                string images = "<tr><td class='w580' width='580'><img src='" + "https://s3-eu-west-1.amazonaws.com/" + company_name.ToLower() + "/" + pair.Value.ToString() + "' label='Image' class='w580' width='580' border='0'></td></tr> Photo_URL";
                text = Regex.Replace(text, "Photo_URL", images);

            }
            text = Regex.Replace(text, "Photo_URL", " ");
            streamReader.Close();

            List<string> ToEmailAddresses = new List<string>();
            ToEmailAddresses.Add(email);

            var client = new AmazonSimpleEmailServiceClient("AKIAIOPVPT5WPQ7CIWGQ", "mub7xYzBD/6VkgxIkyQY0U+6m9DSGTWs74bP6AzM");
            Body bdy = new Body();
            bdy.Html = new Amazon.SimpleEmail.Model.Content(text);
            SendEmailRequest req = new SendEmailRequest()
                .WithDestination(new Destination() { ToAddresses = ToEmailAddresses })
                .WithSource("noreply@securitydev.com.ua")
                .WithReturnPath("noreply@securitydev.com.ua")
                .WithMessage(
                new Amazon.SimpleEmail.Model.Message(new Content("SecurInfo Alarm Email!"),
                bdy));

            var resp = client.SendEmail(req);
        }
 */